package com.yishu.Dao;

import com.yishu.entity.MyBook;
import com.yishu.util.DBConnection;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class MyBookDao {

    DBConnection dbConnection = new DBConnection();

    /**
     * 插入一条买书的记录
     * @param bookId
     * @param userId
     * @return
     * @throws Exception
     */
    public int addShopARecourd(int bookId,int userId) throws Exception {

        Connection connection = dbConnection.getCon();
        String sql = "insert into t_myBooks(userId,bookId) values ('"+userId+"','"+bookId+"')";
        Statement statement = connection.createStatement();
        int result = statement.executeUpdate(sql);

        return result;
    }

    /**
     * 查询用户的购物车
     * @param userId
     * @param connection
     * @return
     * @throws Exception
     */
    public List<MyBook> showAUserShopping(int userId,Connection connection) throws Exception {
        connection = dbConnection.getCon();
        String sql = "select * from t_myBooks where userId = '"+userId+"'";
        Statement statement = connection.createStatement();
        List<MyBook> myBookList = new ArrayList<>();
        ResultSet resultSet = statement.executeQuery(sql);
        while (resultSet.next()) {
            MyBook myBook = new MyBook();
            myBook.setId(resultSet.getInt("id"));
            myBook.setBookId(resultSet.getInt("bookId"));
            myBook.setUserId(resultSet.getInt("userId"));
            myBookList.add(myBook);
        }


        return myBookList;
    }
}
